import json
import uuid
import os

import time
from PIL import Image
import numpy as np
import requests

# picUrl = 'http://mmbiz.qpic.cn/mmbiz_jpg/ZaiaWvumk8xm1tyfJtlealjCwAoDibcRctUbpo72rFOCEljxibO4rYic2fS9pNjzze883q7yu7ia6rjFcKwOuSNwkpQ/0'
# uid = uuid.uuid1()
from get_token import get_access


def cvt(picUrl, uid):
    data = requests.get(picUrl).content
    with open('./images/%s.jpg' % (uid), 'wb') as f:
        f.write(data)

    a = np.asarray(Image.open('./images/%s.jpg' % (uid)).convert('L')).astype('float')

    depth = 10.  # (0-100)
    grad = np.gradient(a)  # 取图像灰度的梯度值
    grad_x, grad_y = grad  # 分别取横纵图像梯度值
    grad_x = grad_x * depth / 100.
    grad_y = grad_y * depth / 100.
    A = np.sqrt(grad_x ** 2 + grad_y ** 2 + 1.)
    uni_x = grad_x / A
    uni_y = grad_y / A
    uni_z = 1. / A

    vec_el = np.pi / 2.2  # 光源的俯视角度，弧度值
    vec_az = np.pi / 4.  # 光源的方位角度，弧度值
    dx = np.cos(vec_el) * np.cos(vec_az)  # 光源对x 轴的影响
    dy = np.cos(vec_el) * np.sin(vec_az)  # 光源对y 轴的影响
    dz = np.sin(vec_el)  # 光源对z 轴的影响

    b = 255 * (dx * uni_x + dy * uni_y + dz * uni_z)  # 光源归一化
    b = b.clip(0, 255)

    im = Image.fromarray(b.astype('uint8'))  # 重构图像
    im.save('./images/%s_1.jpg' % (uid))


def get_media_id(uid):
    token = get_access()
    os.chdir('./images')
    popen = os.popen(
        'curl -F media=@{}_1.jpg "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={}&type=image"'.format(
            uid,token))

    # print(json.loads(popen.read())['media_id'])
    # print(popen.read())
    # print("222"+json.loads(popen.read()))
    # print(json.loads(popen.read())['media_id'])
    os.chdir('..')
    return json.loads(popen.read()).get('media_id')
    # cvt(picUrl,uid)


# cvt(picUrl, uid)
# mediaId = get_media_id(uid)
# print(mediaId)